Stop multiple pipeline runs in Azure DevOps

Thu, October 31, 2024 - 1 min read

Sometime you need to stop hundreds of pipeline runs in Azure DevOps, there is no good way to do this using the az devops cli so you have to resort to REST.

aca_scaling_rules.bicep
 
 
$AzureDevOpsPAT = "***" # Replace the values in this for the variables with your own.
$OrganizationName = "" # Replace the values in this for the variables with your organisation name.
$ProjectName = "" # Replace the values in this for the variables with your project name.
$AzureDevOpsAuthenicationHeader = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
$Uri = "https://dev.azure.com/$($OrganizationName)/$($ProjectName)/_apis/build/builds?statusFilter=Started&api-version=5.1"
$PendingJobs = Invoke-RestMethod -Uri $Uri -Headers $AzureDevOpsAuthenicationHeader -Method get -ContentType "application/json"
$JobsToCancel = $PendingJobs.value
ForEach ($build in $JobsToCancel) {
    $build.status = "Cancelling"
    $body = $build | ConvertTo-Json -Depth 10
    $urlToCancel = "https://dev.azure.com/$($OrganizationName)/$($ProjectName)/_apis/build/builds/$($build.id)?api-version=5.1"
    Invoke-RestMethod -Uri $urlToCancel -Method Patch -ContentType application/json -Body $body -Header $AzureDevOpsAuthenicationHeader
}